package com.diao.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.NettyRuntime;

/**
 * @author: chenzhidiao
 * @date: 2021/4/18 11:26
 * @description: 需求：
 * 服务端启动，监听9000端口
 * 客户端启动，向服务端发送消息
 * 服务端收到客户端消息后，返回响应
 * @version: 1.0
 */
public class NettyServer {
    public void run(int port) throws InterruptedException {

        /**
         * bossGroup 和 workerGroup 默认的 EventLoop 的个数是 CPU Core * 2
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);


        try {
            //创建启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            //设置启动对象的属性，通过构建者模式
            serverBootstrap.group(bossGroup, workerGroup)//设置两个线程组
                    .channel(NioServerSocketChannel.class)//服务端的通道实现类：NioSocketChanne
                    .option(ChannelOption.SO_BROADCAST, true)//设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //向EventLoop关联的ChannelPipelin中添加一个Handler
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });//给EventLoop对应的Pipelin添加处理器
            System.out.println(".....服务器is ready！！！....");

            //绑定一个端口并同步，生成一个ChannelFuture对象
            ChannelFuture cf = serverBootstrap.bind(port).sync();

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } finally {
            //如果发生异常则优雅关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {

        //System.out.println(NettyRuntime.availableProcessors());
        new NettyServer().run(9000);
    }
}
